class CartController < ApplicationController
  before_filter :initialize_cart
  def add
   
    respond_to do |format|
      format.html do
        if request.post?
          @item=@cart.add(params[:id])
          flash[:cart_notice]="选购了<em>#{@item.product.name}</em>"
          redirect_to :back
        else
          @product=@item.product
        end
      end
      format.js do
        @item=@cart.add(params[:id])
       
        flash.now[:cart_notice]="选购了<em>#{@item.product.name}</em>"
        render :action=>"add_with_ajax"
      end
    end
  end
  def remove
    #此时的id是购物项的id
    respond_to do |format|
      format.html do
        if request.post?
          @item=@cart.remove(params[:id])
          flash[:cart_notice]="去除一件<em>#{@item.product.name}</em>"
          redirect_to :back
        else
          @product=@item.product
        end

      end
      format.js do
        @item=@cart.remove(params[:id])      
        flash.now[:cart_notice]="去除了一件<em>#{@item.product.name}</em>"
        render :action=>"remove_with_ajax"
      end
    end
  end
  def clear
    respond_to do |format|
      format.html do
        if request.post?
          @cart.cart_items.destroy_all
          flash[:cart_notice] = "购物车已清空!"
          redirect_to :back
        end
      end
      format.js do
        @cart.cart_items.destroy_all
        flash.now[:cart_notice] = "购物车已清空!"
        render :action => "clear_with_ajax"
      end
    end
    
  end

end
